/*
 * Copyright (c) 2015, FPX and/or its affiliates. All rights reserved.
 * Use, Copy is subject to authorized license.
 */
package org.linetime.netty.chapter01;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.channel.socket.oio.OioServerSocketChannel;
import io.netty.channel.socket.oio.OioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

/**
 * @author sangaiz
 * @date 2019/8/14
 * @since v1.0.0
 */

public class NettyServer {

    public static void main(String[] args) {

        // 负责accept新连接的线程组
        NioEventLoopGroup boss = new NioEventLoopGroup();
        // 负责每一条链接的数据读取处理的线程组
        NioEventLoopGroup worker = new NioEventLoopGroup();
        // 引导类，引导服务端的启动
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap
                // 配置两大线程组，确定线程模型
                .group(boss, worker)
                // 指定服务端的IO模型为NIO，如需设置OIO; 可以使用 OioServerSocketChannel
                // NioServerSocketChannel
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    // 定义每一条连接的数据读写，业务逻辑处理， NioSocketChannel也是Netty对NIO类型的连接的抽象
                    @Override
                    protected void initChannel(NioSocketChannel ch) {
                        // 添加解码器
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, String msg) {
                                System.out.println(msg);
                            }
                        });
                    }
                });
        // 绑定端口
        bind(serverBootstrap, 8000);
    }

    private static void bind(ServerBootstrap bootstrap, final int port) {
        ChannelFuture bind = bootstrap.bind(port);
        if (bind.isSuccess()) {
            System.out.println("绑定成功,端口:" + port);
        } else {
            System.out.println("绑定失败,端口:" + port);
            bind(bootstrap, port + 1);
        }
    }
}
